package pers.corvey.studyjava.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.studyjava.dao.ChoiceDAO;
import pers.corvey.studyjava.dao.QuestionAnswerDAO;
import pers.corvey.studyjava.dao.QuestionDAO;
import pers.corvey.studyjava.model.Choice;
import pers.corvey.studyjava.model.Question;
import pers.corvey.studyjava.model.QuestionAnswer;
import pers.corvey.studyjava.model.json.QuestionAnswerJson;

@Service
public class QuestionService {

    @Autowired
    private QuestionDAO questionDAO;
    
    @Autowired
    private ChoiceDAO choiceDAO;
    
    @Autowired
    private QuestionAnswerDAO questionAnswerDAO;
    
    public Iterable<Question> getQuestions(String testId) {
        return questionDAO.findByTestId(testId);
    }
    
    public Question getQuestionById(String questionId) {
        return questionDAO.findOne(questionId);
    }
    
    public Question createQuestion(Question question) {
        List<Choice> choices = question.getChoices();
        question.setChoices(null);
        question = questionDAO.save(question);
        for (Choice choice : choices) {
            choice.setQuestionId(question.getId());
        }
        choiceDAO.save(choices);
        List<QuestionAnswer> answers = new ArrayList<>();
        for (Choice choice : choices) {
            if (choice.getCorrect() == true) {
                QuestionAnswer answer = new QuestionAnswer();
                answer.setQuestionId(question.getId());
                answer.setChoiceId(choice.getId());
                answers.add(answer);
            }
        }
        questionAnswerDAO.save(answers);
        question.setChoices(choices);
        return question;
    }
    
    public List<QuestionAnswerJson> getAnswersByTestId(String testId) {
        List<QuestionAnswerJson> answerJsons = new ArrayList<>();
        for (Question question : getQuestions(testId)) {
            Iterable<QuestionAnswer> questionAnswers = questionAnswerDAO.findByQuestionId(question.getId());
            QuestionAnswerJson answerJson = new QuestionAnswerJson();
            answerJson.setQuestionId(question.getId());
            answerJson.setChoiceIds(questionAnswers);
            answerJsons.add(answerJson);
        }
        return answerJsons;
    }
    
}
